import { createStore, applyMiddleware, combineReducers } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';

function getReducersMap(name, reducer, reducersMap = {}) {
  const nameArr = name.split('.');
  if (nameArr.length === 1) {
    if (reducersMap[name]) {
      return {
        isInMap: true,
      };
    } else {
      reducersMap[name] = reducer;
    }
  } else if (nameArr.length === 2) {
    const [n1, n2] = nameArr;
    if (reducersMap[n1]) {
      if (reducersMap[n1][n2]) {
        return {
          isInMap: true,
        };
      } else {
        reducersMap[n1][n2] = reducer;
      }
    } else {
      reducersMap[n1] = {
        [n2]: reducer,
      };
    }
  } else {
    console.error('过长的name：', name);
  }
  return {
    reducersMap,
  };
}

// function getReducersMap(name, reducer, reducersMap = {}) {
//   const nameArr = name.split('.');
//   if (nameArr.length === 1) {
//     if (typeof reducer === 'function') {
//       if (typeof reducersMap[name] === 'function') {
//         // const fun = reducersMap[name];
//         reducersMap[name] = reducer;
//       } else {
//         reducersMap[name] = reducer;
//       }
//     } else if (reducer) {
//       reducersMap[name] = {
//         ...reducersMap[name],
//         ...reducer,
//       };
//     } else {
//       delete reducersMap[name];
//     }
//     return reducersMap;
//   } else {
//     const useName = nameArr.shift();
//     reducersMap[useName] = getReducersMap(nameArr.join('.'), reducer, reducersMap[useName]);
//     return reducersMap;
//   }
// }

function deepCopy(obj) {
  const newObj = {};
  Object.keys(obj).forEach((i) => {
    newObj[i] = typeof obj[i] === 'function' ? obj[i] : deepCopy(obj[i]);
  });
  return newObj;
}

function combineMapReducers(rmp) {
  const reducersMap = deepCopy(rmp);
  Object.keys(reducersMap).forEach((v) => {
    if (typeof reducersMap[v] !== 'function') {
      reducersMap[v] = combineMapReducers(reducersMap[v]);
    }
  });
  return combineReducers(reducersMap);
}

const middlewares = [thunkMiddleware];
if (process.env.NODE_ENV === 'development') {
  const loggerMiddleware = createLogger({
    level: 'log',
  });
  middlewares.push(loggerMiddleware);
}

const createStoreWithMdware = applyMiddleware(...middlewares)(createStore);

export default (reducerMap) => {
  const injectAsyncReducers = (store, name, reducers) => {
    const res = getReducersMap(name, reducers, store.asyncReducersMap);
    if (res.isInMap) {
      return;
    }
    store.asyncReducersMap = res.reducersMap;

    // replace all of the reducers in the store, including our new ones
    store.replaceReducer(combineMapReducers({ ...store.asyncReducersMap }));
  };

  // 创建store
  const _store = createStoreWithMdware(combineMapReducers(reducerMap));

  _store.asyncReducersMap = reducerMap;

  _store.registerDynamicModule = ({ name, reducer }) => {
    injectAsyncReducers(_store, name, reducer);
  };

  _store.unRegisterDynamicModule = (name) => {
    // console.log(`注销动态模块${name}:`);
    injectAsyncReducers(_store, name, null);
  };

  return _store;
};
